import request from '@/utils/request'

import { ref } from 'vue'

import { systemApi } from '@/api'

/**
 * 数据字典工具类
 */
export default class Dict {
  constructor(dict) {
    this.dict = dict
  }

  /**
   * 获取字典数据
   */
  async init() {
    const responses = await Promise.all(this.dict.map(d => {
      return systemApi.getDictData(d)
    }))
    const result = responses.map((res, index) => {
      return {
        key: this.dict[index],
        value: ref(res.map(item => ({
          label: item.dictLabel,
          value: item.dictValue,
          listClass: item.listClass,
          cssClass: item.cssClass,
          remark: item.remark
        })))
      }
    })
    
    return Object.fromEntries(result.map(({key, value}) => [key, value]))
  }
}

export function useDict(...args) {
  const dict = new Dict(args)
  return dict.init()
}

/**
 * 获取字典数据项的标签
 * @param {Array} dicts 字典数据列表
 * @param {String|Number} value 字典值
 * @returns {String} 标签
 */
export function getDictLabel(dicts, value) {
  if (!dicts || !Array.isArray(dicts)) return ''
  const data = dicts.find(dict => dict.value === value)
  return data ? data.label : ''
}

/**
 * 获取字典数据项的值
 * @param {Array} dicts 字典数据列表
 * @param {String} label 字典标签
 * @returns {String|Number} 值
 */
export function getDictValue(dicts, label) {
  if (!dicts || !Array.isArray(dicts)) return ''
  const data = dicts.find(dict => dict.label === label)
  return data ? data.value : ''
}

/**
 * 获取字典数据项的类型样式
 * @param {Array} dicts 字典数据列表
 * @param {String|Number} value 字典值
 * @returns {String} 样式名称
 */
export function getDictClass(dicts, value) {
  if (!dicts || !Array.isArray(dicts)) return ''
  const data = dicts.find(dict => dict.value === value)
  return data ? data.listClass : ''
}

/**
 * 获取字典数据项的类型标记
 * @param {Array} dicts 字典数据列表
 * @param {String|Number} value 字典值
 * @returns {String} 标记类型
 */
export function getDictType(dicts, value) {
  if (!dicts || !Array.isArray(dicts)) return ''
  const data = dicts.find(dict => dict.value === value)
  return data ? data.cssClass : ''
}

/**
 * 获取字典数据项的备注说明
 * @param {Array} dicts 字典数据列表
 * @param {String|Number} value 字典值
 * @returns {String} 备注说明
 */
export function getDictRemark(dicts, value) {
  if (!dicts || !Array.isArray(dicts)) return ''
  const data = dicts.find(dict => dict.value === value)
  return data ? data.remark : ''
}

/**
 * 获取字典数据项的标签和备注
 * @param {Array} dicts 字典数据列表
 * @param {String|Number} value 字典值
 * @returns {String} 标签和备注
 */
export function getDictLabelWithRemark(dicts, value) {
  if (!dicts || !Array.isArray(dicts)) return ''
  const data = dicts.find(dict => dict.value === value)
  if (!data) return ''
  return `${data.label}${data.remark ? `（${data.remark}）` : ''}`
} 